package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class FreezeMovementInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     *拦截发布动态
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截用户: " + UserHolder.getUserId() + " 发布动态");
        String method = request.getMethod();
        if ("POST".equalsIgnoreCase(method)) {
            String s = redisTemplate.opsForValue().get("FREEZE_TYPE_" + UserHolder.getUserId());
            if ("3".equals(s)) {
                response.setStatus(500);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = null;
                JSONObject res = new JSONObject();
                res.put("errCode", "0097");
                res.put("errMessage", "已被限制发布动态");
                out = response.getWriter();
                out.append(res.toString());
                return false;
            }
        }
        return true;
    }
}
